from django import forms
from blog.models import *
from django.core.exceptions import ValidationError


"""
RegisteForm:
    username
    password
    repassword
    nickname
    email
    telephone
    head_img
    
"""


class RegisteForm(forms.Form):
    username = forms.CharField(label='登录账号', max_length=20, error_messages={'max_length': '长度不能超过20位', 'required': '登录账号不能为空'},
                               widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(label='密码', min_length=6,
                               error_messages={'min_length': '密码不能少于6位', 'required': '密码不能为空'},
                               widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'}, render_value=True))
    repassword = forms.CharField(label='确认密码', min_length=6,
                                 error_messages={'min_length': '密码不能少于6位', 'required': '密码不能为空'},
                                 widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'}, render_value=True))
    nickname = forms.CharField(label='昵称', max_length=20, required=False,
                               error_messages={'max_length': '昵称不能超过20位'}, initial='无名氏',
                               widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
    email = forms.EmailField(label='邮箱', error_messages={'invalid': '邮箱格式不争取', 'required': '邮箱不能为空'},
                             widget=forms.widgets.EmailInput(attrs={'class': 'form-control'}))
    telephone = forms.CharField(label='电话号码', required=False, error_messages={'max_length': '最大长度不能超过11位'},
                                widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
    head_img = forms.ImageField(label='头像', widget=forms.widgets.FileInput(attrs={'style': 'display:none'}))

    def clean_username(self):
        uname = self.cleaned_data.get('username')
        vexist = Loguser.objects.filter(username=uname)
        if vexist:
            self.add_error('username', ValidationError('用户名已存在!'))
        else:
            return uname

    def clean_repassword(self):
        passwd = self.cleaned_data.get('password')
        repasswd = self.cleaned_data.get('repassword')

        if repasswd != passwd:
            self.add_error('repassword', ValidationError('两次输入的密码不一致'))
        else:
            return repasswd


class LoginForm(forms.Form):
    username = forms.CharField(label='登录账号', max_length=20,
                               error_messages={'max_length': '长度不能超过20位', 'required': '登录账号不能为空'},
                               widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(label='密码', min_length=6,
                               error_messages={'min_length': '密码不能少于6位', 'required': '密码不能为空'},
                               widget=forms.widgets.PasswordInput(attrs={'class': 'form-control'}, render_value=True))